package ai.people.platform.archives.service.impl;

import ai.people.netmon.framework.domain.archives.entity.ArchivesImages;
import ai.people.netmon.framework.exception.enums.CommonEnum;
import ai.people.netmon.framework.exception.enums.PictureExceptionEnum;
import ai.people.netmon.framework.utils.AssertUtils;
import ai.people.netmon.utils.Base64Utils;
import ai.people.netmon.utils.PictureUtils;
import ai.people.platform.archives.mapper.ArchivesImagesMapper;
import ai.people.platform.archives.service.ArchivesImagesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhenglin
 * @since 2022-04-12
 */
@Service
public class ArchivesImagesServiceImpl extends ServiceImpl<ArchivesImagesMapper, ArchivesImages> implements ArchivesImagesService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveImg(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        boolean check = PictureUtils.checkSuffix(originalFilename);
        AssertUtils.isTrue(check, PictureExceptionEnum.IMG_SUFFIX_NOT_SUPPORT);

        ArchivesImages images = new ArchivesImages();
        images.setContent(file.getBytes());

        boolean save = save(images);
        AssertUtils.isTrue(save, CommonEnum.FAIL);
        return images.getId().toString();
    }

    @Override
    public String getImg(Long id) {
        ArchivesImages byId = getById(id);
        AssertUtils.isNotNull(byId,CommonEnum.QUERY_NOT_FOUND);
        byte[] content = byId.getContent();
        return Base64Utils.ENCODER.encodeToString(content);
    }
}
